const router=require('koa-router')();
const fs=require('fs');

function getRouteFiles(filesPath) {
    let tmpPath=filesPath ||__dirname;
    let files=fs.readdirSync(tmpPath);
    let RouteFiles=files.filter(item=>{
        return item.endsWith('.js') && item !=='index.js';      
    })
    return RouteFiles;
}

function registryRoute(router,routeFiles) {
    routeFiles.forEach(item => {
        let tmpPath=__dirname+'/'+item;
        let obj=require(tmpPath);

        for(let key in obj)
        {
            let tmpArr=key.split(' ');
            let rMethod=tmpArr[0];
            let rPath=tmpArr[1];
            let rFunction=obj[key];

            if (rMethod==='get') {
                router.get(rPath,rFunction);

            }else if (rMethod==='post') {
                router.post(rPath,rFunction);
            }else if (rMethod==='put') {
                router.put(rPath,rFunction);
            }else if (rMethod==='delete') {
                router.delete(rPath,rFunction);
            }else {
                console.log('请检查路径是否正确');
            }
        }
    });

    return router.routes();
} 


module.exports=function () {
    let routeFiles=getRouteFiles();
    let fn=registryRoute(router,routeFiles);
    return fn;
}